import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:live_bg_mobile/common/util/common_util.dart';

import '../../common/api/site_api.dart';
import '../../common/enum/btn_enum.dart';
import '../../common/type/address_picker_type.dart';
import '../../widget/address_picker.dart';
import '../../widget/card_container.dart';
import '../../widget/form_item.dart';
import '../../widget/icon_outlined_btn.dart';
import '../../widget/input_field.dart';
import '../../widget/img_upload_list.dart';

class SiteAddPage extends StatefulWidget {
  final Map arguments;

  const SiteAddPage({Key? key, required this.arguments}) : super(key: key);

  @override
  State<SiteAddPage> createState() => SiteAddPageState();
}

class SiteAddPageState extends State<SiteAddPage> {
  AddressPickerType city = AddressPickerType();
  List<String> imgList = [];
  String id = '';

  TextEditingController nameCtrl = TextEditingController();
  TextEditingController cityCtrl = TextEditingController();
  TextEditingController telCtrl = TextEditingController();
  TextEditingController addressDetailCtrl = TextEditingController();
  TextEditingController desCtrl = TextEditingController();

  @override
  void initState() {
    super.initState();
    initData();
  }

  @override
  void dispose() {
    super.dispose();
    nameCtrl.dispose();
    cityCtrl.dispose();
    telCtrl.dispose();
    addressDetailCtrl.dispose();
    desCtrl.dispose();
  }

  initData() {
    if (null != widget.arguments["id"] && "" != widget.arguments["id"]) {
      id = widget.arguments["id"].toString();

      SiteApi.getLiveLoc({"id": id}).then((res) {
        if (null != res.data && res.data["isSuccess"]) {
          var data = res.data["data"];
          nameCtrl.text = data["name"] ?? '';
          telCtrl.text = data["contactTel"] ?? '';
          addressDetailCtrl.text = data["addressDetail"] ?? '';
          desCtrl.text = data["des"] ?? '';

          city.provinceId = (data["provinceId"] ?? '').toString();
          city.province = data["provinceName"] ?? '';
          city.cityId = (data["cityId"] ?? '').toString();
          city.city = data["cityName"] ?? '';
          city.areaId = (data["areaId"] ?? '').toString();
          city.area = data["areaName"] ?? '';

          cityCtrl.text = city.province + city.city + city.area;

          imgList =
              ((data['locPicList'] ?? []) as List<dynamic>).cast<String>();
          setState(() {});
        } else {
          CommonUtil.showToast(res.data["msg"]);
        }
      });
    }
  }

  void save() {
    if (nameCtrl.text.trim().isEmpty) {
      CommonUtil.showToast("请输入基地名称！");
      return;
    }

    if (telCtrl.text.trim().isEmpty) {
      CommonUtil.showToast("请输入联系电话！");
      return;
    }

    if (!CommonUtil.isChinaPhoneLegal(telCtrl.text.trim())) {
      CommonUtil.showToast("联系电话格式不正确！");
      return;
    }

    if ("" == city.areaId && "" == city.cityId && "" == city.provinceId) {
      CommonUtil.showToast("请选择地区！");
      return;
    }

    if (addressDetailCtrl.text.trim().isEmpty) {
      CommonUtil.showToast("请输入详细地址！");
      return;
    }

    if (imgList.isEmpty) {
      CommonUtil.showToast("请添加门面图片！");
      return;
    }

    Map data = {
      "id": id,
      "provinceName": city.province,
      "provinceId": city.provinceId,
      "cityName": city.city,
      "cityId": city.cityId,
      "areaName": city.area,
      "areaId": city.areaId,
      "name": nameCtrl.text,
      "addressDetail": addressDetailCtrl.text,
      "des": desCtrl.text,
      "fullAddressInfo":
          city.province + city.city + city.area + addressDetailCtrl.text,
      "locPicList": imgList,
      "contactTel": telCtrl.text,
    };

    SiteApi.saveLiveLoc(data).then((res) {
      if (null != res.data && res.data["isSuccess"]) {
        Navigator.of(context).pushNamed("/siteManagement");
      } else {
        CommonUtil.showToast(res.data["msg"]);
      }
    });
  }

  Future addressActionSheet() {
    return showModalBottomSheet(
      context: context,
      builder: (ctx) {
        return AddressPicker(onChecked: (res) {
          if ("" == res.areaId && "" == res.cityId && "" == res.provinceId) {
            CommonUtil.showToast("请选择地区！");
            return false;
          }

          return true;
        }, onResult: (res) {
          CommonUtil.textInputHide();
          city = res;
          cityCtrl.text = res.province + res.city + res.area;
        });
      },
    );
  }

  siteAddBodyBuilder(context) {
    return Column(children: [
      InputField(
        controller: nameCtrl,
        inputFormatters: [LengthLimitingTextInputFormatter(50)],
        hintText: '请输入基地名称',
        labelText: '基地名称',
      ),
      InputField(
        controller: telCtrl,
        keyboardType: TextInputType.phone,
        inputFormatters: [LengthLimitingTextInputFormatter(11)],
        hintText: '请输入联系电话',
        labelText: '联系电话',
      ),
      InputField(
        controller: cityCtrl,
        hintText: '请通过右侧按钮选择所在地区',
        labelText: '地区',
        readOnly: true,
        suffixIcon: IconButton(
          icon: const Icon(Icons.keyboard_arrow_down_sharp),
          onPressed: () {
            addressActionSheet();
          },
        ),
      ),
      InputField(
        controller: addressDetailCtrl,
        inputFormatters: [LengthLimitingTextInputFormatter(100)],
        maxLines: 5,
        minLines: 5,
        hintText: '请输入详细地址',
        labelText: '详细地址',
      ),
      InputField(
        controller: desCtrl,
        inputFormatters: [LengthLimitingTextInputFormatter(100)],
        maxLines: 5,
        minLines: 5,
        hintText: '请输入描述',
        labelText: '描述',
      ),
      const FormItem(
        label: '门面图片',
      ),
      ImgUploadList(
          fileList: imgList,
          onUpdateFileList: (list) {
            imgList = list;
          }),
      Padding(
          padding: const EdgeInsets.only(top: 10.0),
          child: IconOutlinedBtn(
              text: '提交',
              btnType: BtnType.primary,
              onPressed: () {
                save();
              }))
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("基地添加"),
      ),
      body: SingleChildScrollView(
          controller: ScrollController(),
          child: Padding(
              padding: const EdgeInsets.all(10.0),
              child: GestureDetector(
                onTap: () {
                  CommonUtil.cancelFocusNodes(context);
                },
                child: CardContainer(
                    margin: const EdgeInsets.only(bottom: 10.0),
                    bodyBuilder: (context) => siteAddBodyBuilder(context)),
              ))),
    );
  }
}
